<!--
Copyright (c) 2022 Huawei Device Co., Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->



<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8">
    <link rel="shortcut icon" href="audio/hellokunwebmiao.jpg">
    <title>OpenHarmony-iot</title>

    <link href="css/har.css" type="text/css" rel="stylesheet" />

    <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css"/>
    <style>
        html,body,#container{
            height:100%;
            width:100%;
        }
        .amap-icon img{
            width: 25px;
            height: 34px;
        }
        .amap-marker-label{
            border: 0;
            font-size: 20px;
            font-color: 'blue';
            background-color: 'white';
            background-color: 'white';

        }
        .info{
            position: relative;
            margin:0;
            top: 0;
            right: 0;
            min-width: 0;
        }
    </style>

    </style>
</head>
<body>
<!--<input type="text" id="msg" />-->
<!--<div>连接状态：<span id="status"></span></div>-->
<!--<div>收到信息: <span id="getMsg"></span> </div>-->
<!--<div>经度START_J: <span id="START_J"></span> </div>-->
<!--<div>纬度START_W: <span id="START_W"></span> </div>-->
<!--<div>当前位置: <span id="PositionName"></span> </div>-->
<!--<button type="button" onclick="startDraw()">Click Me!</button>-->
<!--<div class="sketchfab-embed-wrapper"> <iframe title="Valley Pond" frameborder="0" allowfullscreen mozallowfullscreen="true" webkitallowfullscreen="true" allow="autoplay; fullscreen; xr-spatial-tracking" xr-spatial-tracking execution-while-out-of-viewport execution-while-not-rendered web-share src="https://sketchfab.com/models/d7bf45d6e5ad422b949d58140fae13f7/embed"> </iframe> <p style="font-size: 13px; font-weight: normal; margin: 5px; color: #4A4A4A;"> <a href="https://sketchfab.com/3d-models/valley-pond-d7bf45d6e5ad422b949d58140fae13f7?utm_medium=embed&utm_campaign=share-popup&utm_content=d7bf45d6e5ad422b949d58140fae13f7" target="_blank" rel="nofollow" style="font-weight: bold; color: #1CAAD9;"> Valley Pond </a> by <a href="https://sketchfab.com/MaconPonds?utm_medium=embed&utm_campaign=share-popup&utm_content=d7bf45d6e5ad422b949d58140fae13f7" target="_blank" rel="nofollow" style="font-weight: bold; color: #1CAAD9;"> Macon Ponds </a> on <a href="https://sketchfab.com?utm_medium=embed&utm_campaign=share-popup&utm_content=d7bf45d6e5ad422b949d58140fae13f7" target="_blank" rel="nofollow" style="font-weight: bold; color: #1CAAD9;">Sketchfab</a></p></div>-->
<div id="container"></div>


<script type="text/javascript">
        window._AMapSecurityConfig = {
            securityJsCode:'dcd9d59a9d2e5b9a6243edadaa3a429d',
        }
</script>
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=474b1994596871c3834a7bf7e91a1297&plugin=AMap.Geocoder"></script>
<!--<script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=474b1994596871c3834a7bf7e91a1297"></script>-->
<script type="text/javascript">

    var publish_topic="PilotWeb";
    var subscribe_topic = "PilotDevice";
    var START_J = '121.498586'
    var START_W = '31.239637'
    var Position = '0'
    var PositionName = '正在定位，等待刷新地点...'
    var getAddressCount = 4990
    var IsGPS = 0  //使用GPS定位 位置精确但信号不稳定
    var Is4G  = 1  //使用基站定位 位置不精准但信号相对稳定
    var PilotPower = '88'
    var PilotTemp = '33.4'

    // 创建地图实例
    var map = new AMap.Map("container", {
        zoom: 18, // 缩放
        center: [START_J, START_W], //初始地图中心点为上海
        resizeEnable: true
    });

        // 创建纯文本标记
    var text = new AMap.Text({
        text: PositionName,
        anchor:'center', // 设置文本标记锚点
        draggable:true,
        cursor:'pointer',
        angle:0,
        style:{
            'padding': '0.75rem 1.25rem',
            'margin-bottom': '11rem',
            'margin-left': '5rem',
            'border-radius': '.25rem',
            'background-color': 'white',
            'width': '75rem',
            'border-width': 0,
            'box-shadow': '0 2px 6px 0 rgba(114, 124, 245, .5)',
            'text-align': 'center',
            'font-size': '26px',
            'color': 'blue'
        },
        position: [this.START_J, this.START_W]
    });
     text.setMap(map);

    // 创建一个 Icon
    var startIcon = new AMap.Icon({
        // 图标尺寸
        size: new AMap.Size(100, 100),
        // 图标的取图地址
        image: './img/rider.png',
        // 图标所用图片大小
        imageSize: new AMap.Size(100, 100),
        // 图标取图偏移量
        // imageOffset: new AMap.Pixel(-19, -13)
    });

    // 将 icon 传入 marker
    var startMarker = new AMap.Marker({
        position: new AMap.LngLat(this.START_J, this.START_W),
        icon: startIcon,
        offset: new AMap.Pixel(-13, -30)
    });
    map.add([startMarker]);

    // 创建一个地理编码实例
    var geocoder = new AMap.Geocoder({
        city: "010", //城市设为北京，默认：“全国”
        radius: 1000 //范围，默认：500
    });
// 供 ets 调用函数
// 开启定位
function subscribeGPS()
{
    this.subscribe();
    // map && map.destroy();  // 销毁地图
}
// 关闭定位
function unsubscribeGPS()
{
     this.unsubscribe();
}
// 车辆解锁
function UnLock()
{
    this.send('unlock',"PilotWeb");
}
// 车辆上锁
function Lock()
{
    this.send('lock',"PilotWeb");
}
// 车辆响铃
function RingOn()
{
    this.send('ring_on',"PilotWeb");
}
// 车辆关铃
function RingOff()
{
    this.send('ring_off',"PilotWeb");
}

// 车辆开灯
function LightOn()
{
    this.send('light_on',"PilotWeb");
}
// 车辆关灯
function LightOff()
{
    this.send('light_off',"PilotWeb");
}


    const options={
        connectTimeout:4000,
        keepalice:20,
        clean:true,
        clientId:'mqttjsks6',
        username:'hellokun',
        password:'123456',
    }
    const client=mqtt.connect('ws://120.55.170.12:8083/mqtt',options)

    client.on('reconnect', (error) => {
     // document.getElementById("status").innerText = '正在重连';
     console.log('正在重连:', error)
     })

    client.on('error',(error)=>{
        // document.getElementById("status").innerText='Faild';
        console.log('connect faild:',error)
    })

    client.on('connect', (e) => {
        // document.getElementById("status").innerText = '成功';
        console.log('成功连接服务器');
        // 监听接收消息事件
        this.subscribe();
        client.on('message', (topic, message) => {
            console.log('收到来自', topic, '的消息', message.toString())
            if(topic=="PilotDeviceM5"){
                 // aaa.9347534_bbb.5489959|93|27.3 // 坐标、电量、温度
                 this.Position = message.toString().split('_b'); //
                 PilotPower = this.Position.toString().substring(22,24); // 末尾是电量2+温度4位
                 PilotTemp= this.Position.toString().substring(24,28);
                 console.log('电量数据PilotPower'+PilotPower)
                 console.log('温度数据PilotPower'+PilotTemp)
                 this.PostMsgToEts(PilotPower+PilotTemp); // 电量+温度+位置
            }
            else{
                PositionName = '定位成功，等待刷新地点...'
               //  document.getElementById("getMsg").innerText = message.toString();
                 if(IsGPS)
                 {
                    console.log('GPS定位数据')
                    this.Position = message.toString().split('_'); // GPS定位
                    console.log('GPS定位数据Position'+ Position)
                    PilotPower = this.Position.substring(16); // 末尾是电量
                    console.log('电量数据PilotPower'+PilotPower)
                    this.START_J = message.toString().substring(0,8)//GPS定位
                    console.log('GPS定位数据START_J'+START_J)
                    this.START_W = message.toString().substring(9,16)//GPS定位
                    console.log('GPS定位数据START_W'+START_W)
                 }
                 else
                 {
                    console.log('4G基站定位数据')
                    this.Position = message.toString().split('_0'); // 基站定位
                     console.log('基站定位数据Position'+ Position)
                    // PilotPower = this.Position.toString().substring(22,24); // 末尾是电量2+温度4位
                   //  PilotTemp= this.Position.toString().substring(24,28);
                     console.log('电量数据PilotPower'+PilotPower)
                     console.log('温度数据PilotPower'+PilotTemp)
                    this.START_J = message.toString().substring(0,10)// 基站定位
                    console.log('基站定位数据START_J'+START_J)
                    this.START_W = message.toString().substring(13,23)// 基站定位
                    console.log('基站定位数据START_J'+START_W)
                 }
                // document.getElementById("START_J").innerText = this.START_J
                // document.getElementById("START_W").innerText = this.START_W
                if(this.START_J.substring(0,1) !=='0')  //经度首位不为0说明定位成功
                {
                    console.log('this.START_J.substring(0,1) !==0 坐标正确')
                    this.DisplayMap() // 刷新地图
                }

                console.log("niubility!!!!!");
                // document.getElementById("msg").value = "123456\r\n";
                this.send(Position.toString(),"PilotCtrBeep");

            }


         })
     })

     //订阅话题
     function subscribe() {
         if (client.connected) {
             client.subscribe(this.subscribe_topic);
             client.subscribe("PilotDeviceM5");
            // document.getElementById("status").innerText = '开始订阅';
         }
     }
     //取消订阅话题
     function unsubscribe() {
         if (client.connected) {
             client.unsubscribe(this.subscribe_topic, (error) => {
                 console.log(error || '取消订阅')
                // document.getElementById("status").innerText = '取消订阅';
             })
        }
    }

    //发布话题数据
     function send(data,what_topic) {
         // what_topic = "PilotWeb";
         console.log('send(data) from topic:'+what_topic);
         var test = '8888' //document.getElementById("msg").value;
         if (data.length > 0) {
             client.publish(what_topic, data, (error) => {
                console.log(error || '消息发布成功')
             })
            // document.getElementById("msg").value = "";
             console.log("消息发送成功" + data);
         } else {
            alert("发送的消息不能为空");
         }
     }

     function DisplayMap() {
        map.setCenter([this.START_J, this.START_W]); //更新-设置地图中心点为定位坐标
        console.log('this.START_J.substring(0,1) !==0 坐标正确')
        map.add([startMarker]);


        this.getAddressCount += 1;
        console.log('逆编码定位次数'+this.getAddressCount.toString());
        // 地址逆编码 每天5000次限额 注意频率
        if(this.getAddressCount >=5000)
        {
            PositionName = Position + '地址逆编码超5000次/日'+this.getAddressCount.toString();
            text.setText(PositionName);
            return;
        }
        else
        {
            console.log('正在根据经纬度查询地址')
            PositionName  = '正在根据经纬度查询地址'
            geocoder.getAddress(Position, function(status, result) {
                if (status === 'complete'&&result.regeocode) {
                      var address = result.regeocode.formattedAddress;
                      // document.getElementById('PositionName').innerText = address;
                      PositionName = address.toString()
                      console.log('根据经纬度查询地址为：'+ address.toString())

                }else{
                      console.log('根据经纬度查询地址失败')
                      PositionName = '地址逆编码失败';
                }
                // 设置鼠标划过点标记显示的文字提示
                startMarker.setTitle(PositionName);

                // 设置label标签
                // label默认蓝框白底左上角显示，样式className为：amap-marker-label
                var labelOffset = new AMap.Pixel(0, -5);
                var labelContent = "<div class='labelContent'>当前位置:"+PositionName+"</div>"
                startMarker.setLabel({
                    direction:'right',
                    offset: new AMap.Pixel(10, 0),  //设置文本标注偏移量
                    content:  labelContent, //设置文本标注内容
                });
                text.setPosition([this.START_J, this.START_W]);
                text.setText(PositionName);
                // 将 markers 添加到地图
                startMarker.setPosition([this.START_J, this.START_W]);
                map.add([this.startMarker]);

                console.info('发送到ETS:'+PilotPower+PositionName);
                this.PostMsgToEts(PilotPower+PilotTemp); // 电量+温度+位置
             });
        }

    }

var h5Port;
var output = document.querySelector('.output');
window.addEventListener('message', function (event) {
    if (event.data === '__init_port__') {
        if (event.ports[0] !== null) {
            h5Port = event.ports[0]; // 1. 保存从ets侧发送过来的端口
            h5Port.onmessage = function (event) {
              // 2. 接收ets侧发送过来的消息.
              var msg = 'Got message from ets:';
              var result = event.data;
              if (typeof(result) === 'string') {
                console.info(`received string message from html5, string is: ${result}`);
                msg = result;
              } else if (typeof(result) === 'object') {
                if (result instanceof ArrayBuffer) {
                  console.info(`received arraybuffer from html5, length is: ${result.byteLength}`);
                  msg = msg + 'lenght is ' + result.byteLength;
                } else {
                  console.info('not support');
                }
              } else {
                console.info('not support');
              }
              console.info(msg.toString());
              // this.PositionName  = msg.toString();
              // document.getElementById("getMsg").innerText =  msg;
              // send(msg.toString(),"PilotWeb"); //将收到的数据通过mqtt发送到设备。ets可直接调用H5函数，该接口备用
            }
        }
    }
})

// 3. 使用h5Port往ets侧发送消息.
function PostMsgToEts(data) {
    console.info('H5 to Ets data:'+data);
    if (h5Port) {
      h5Port.postMessage(data);
    } else {
      console.error('h5Port is null, Please initialize first');
    }
}

</script>

</body>
</html>